package com.polaris.live.ui.live.widget

import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.LinearLayout
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.R
import com.polaris.live.adapter.live.LiveConsumeAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.dp
import com.polaris.live.common.ext.formatNumberWithK
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.util.DebounceHelper
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.constant.LiveConst
import com.polaris.live.constant.LiveConst.LivePage
import com.polaris.live.databinding.WidgetLiveHeaderBinding
import com.polaris.live.im.sfs.bean.live.CallSignalingMessage
import com.polaris.live.im.sfs.bean.live.LiveRoomInfo
import com.polaris.live.im.sfs.bean.live.ext.UserBasicVo
import com.polaris.live.interface_bag.PAGViewListener
import com.polaris.live.resp.back_resp.CallVo
import com.polaris.live.resp.back_resp.LiveConsumptionUserVo
import com.polaris.live.translation.R.string
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.LiveUtils
import com.polaris.live.utils.RichCharmImgUtil
import com.polaris.live.widget.avatar.FrameImageUtils
import com.polaris.live.widget.pag.AddFollowView.Companion.LIVE_ADD_FOLLOWE
import org.libpag.PAGScaleMode
import org.libpag.PAGView

/**
 * LiveHeaderView
 *
 * @author Created by lucas on 2023/11/7 14:41
 */
class LiveHeaderView(context: Context, attributeSet: AttributeSet) :
    LinearLayout(context, attributeSet) {

    val mBinding = WidgetLiveHeaderBinding.inflate(LayoutInflater.from(context), this)

    //顶部消费列表
    private val mConsumeAdapter by lazy { LiveConsumeAdapter() }

    init {
        orientation = HORIZONTAL
        gravity = Gravity.CENTER_VERTICAL
    }

    fun initData(@LivePage page: Int, callInfo: CallVo, userBasic: UserBasicVo) {
        initData(page, userBasic)
        setUserFollower(callInfo.follow)
        callInfoHandle(callInfo, userBasic.sex, userBasic.richs, userBasic.charms)
    }

    fun initData(@LivePage page: Int, callInfo: CallVo, callMessage: CallSignalingMessage) {
        initUI(
            page,
            callMessage.nicknameColor,
            callMessage.nickname,
            callMessage.sex,
            callMessage.richs,
            callMessage.charms,
            callMessage.vipLevel,
            callMessage.country
        )
        callInfo.gameType?.let {
            setGameType(it)
        }
        setUserFollower(callInfo.follow)
        callInfoHandle(callInfo, callMessage.sex, callMessage.richs, callMessage.charms)
        setAvatar(callMessage.avatar, callMessage.sender, callMessage.avatarFrame)

    }

    private fun callInfoHandle(callInfo: CallVo, sex: Int, richs: Long, charms: Long) {
        if (callInfo.payUserId == UserManager.getUserId()) {
            mBinding.tvUserCount.visibility = GONE
            if (CommonUtils.isMan(sex)) {
                mBinding.lvLevel.setRichsLevel(richs)
            } else {
                mBinding.lvLevel.setCharmsLevel(charms)
            }
        }
    }

    fun initData(@LivePage page: Int, userBasic: UserBasicVo) {
        initUI(
            page,
            userBasic.nicknameColor,
            userBasic.nickname,
            userBasic.sex,
            userBasic.richs,
            userBasic.charms,
            userBasic.vipLevel,
            userBasic.country
        )
        setAvatar(userBasic.avatar, userBasic.userId, userBasic.avatarFrame)
    }

    fun initData(@LivePage page: Int, variable: LiveRoomInfo, userCount: Int) {
        initUI(
            page,
            variable.nicknameColor,
            variable.nickname,
            variable.sex,
            variable.richs,
            variable.charms,
            variable.vipLevel,
            variable.country
        )

        if (page == LiveConst.Page.LIVE_ANCHOR || page == LiveConst.Page.LIVE_SPECTATOR) {
            updateUserCount(userCount - 1)
        }
        setRoomUi(variable.type, variable.gameType)

        setAvatar(variable.avatar, variable.userId, variable.avatarFrame)
    }

    private fun setRoomUi(type: Int, gameType: Int?) {
        when (type) {
            LiveConst.Type.PARTY_LIVE -> {
                mBinding.tvRoomType.text = StringUtils.getString(string.party)
                mBinding.tvRoomType.visibility = View.VISIBLE
                mBinding.lvLevel.visibility = View.GONE
            }

            LiveConst.Type.VIDEO_PARTY -> {
                mBinding.tvRoomType.text = StringUtils.getString(string.video_party)
                mBinding.tvRoomType.visibility = View.VISIBLE
                mBinding.lvLevel.visibility = View.GONE
            }

            LiveConst.Type.PARTY_GAME_LIVE -> {
                gameType?.let {
                    setGameType(it)
                }
            }
        }

    }

    private fun setGameType(gameType: Int) {
        mBinding.tvRoomType.text = when (gameType) {
            LiveConst.GameType.DOMINO -> {
                LiveConst.GameName.DOMINO
            }

            LiveConst.GameType.LUDO -> {
                LiveConst.GameName.LUDO
            }

            LiveConst.GameType.UNNO -> {
                LiveConst.GameName.UNNO
            }

            LiveConst.GameType.BLACK8 -> {
                LiveConst.GameName.BLACK8
            }

            LiveConst.GameType.UNOPRO -> {
                LiveConst.GameName.UNOPRO
            }

            LiveConst.GameType.JELLYBOOM -> {
                LiveConst.GameName.JELLYBOOM
            }

            else -> {
                ""
            }
        }
        mBinding.tvRoomType.visibility = View.VISIBLE
        mBinding.lvLevel.visibility = View.GONE
    }

    private fun setAvatar(avatar: String, userId: Long? = null, avatarFrame: String? = null) {
        mBinding.avAvatar.setImageUrl(avatar, userId)
        mBinding.avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(avatarFrame))
        avatarFrame?.run {
            val lp = mBinding.bgImg.layoutParams as ConstraintLayout.LayoutParams
            lp.marginStart = 5.dp
            mBinding.bgImg.layoutParams = lp
        }
    }

    private fun initUI(
        page: Int,
        nicknameColor: String?,
        nickname: String,
        sex: Int,
        richs: Long,
        charms: Long,
        vipLevel: Long?,
        country: String?,
    ) {
        mBinding.apply {
            if (rvRecycler.layoutManager == null) {
                mBinding.rvRecycler.apply {
                    layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
                    adapter = mConsumeAdapter
                }
            }

            tvNickname.text = nickname
            val color = RichCharmImgUtil.serColor2HexColor(nicknameColor) ?: ColorUtils.getColor(R.color.white)
            tvNickname.setTextColor(color)

            pagView.setPathType(LIVE_ADD_FOLLOWE)
            if (page == LiveConst.Page.CALL) {
                lvLevel.visibility = GONE
                cvCountry.visibility = VISIBLE
                ViewUtils.setMargin(tvTime, leftMargin = 2.dp)

                cvCountry.setCountry(country)

            } else {
                lvLevel.visibility = VISIBLE
                cvCountry.visibility = GONE

                if (CommonUtils.isMan(sex)) {
                    lvLevel.setRichsLevel(richs)
                } else {
                    lvLevel.setCharmsLevel(charms)
                }
            }
            vipView.setVipLevel(vipLevel)
        }
    }

    /**
     * 判断是否关注过
     */
    fun setUserFollower(isFollow: Boolean?) {
        if (isFollow != null) {
            if (isFollow) {
                mBinding.pagView.visibility = View.GONE
            } else {
                mBinding.pagView.visibility = View.VISIBLE
            }
        }
    }

    fun updateConsumeList(list: List<LiveConsumptionUserVo>) {
        if (mConsumeAdapter.data != list) {
            mConsumeAdapter.setList(list)
        }
    }

    /**
     * 更新直播间人数，只有观众
     */
    fun updateUserCount(userCount: Int) {
        mBinding.tvUserCount.apply {
            if (visibility != VISIBLE) {
                visibility = VISIBLE
            }
            text = userCount.formatNumberWithK()
        }
    }

    /**
     * 更新通话时间，只有女接通方
     */
    fun updateTime(elapsedTime: Long) {
        if (!mBinding.tvTime.isVisible) {
            mBinding.tvTime.visibility = View.VISIBLE
        }
        mBinding.tvTime.apply {
            text = LiveUtils.formatTime(elapsedTime)
        }
    }

    fun updateFollowStatus(isFollow: Boolean) {
        if (isFollow) {
            mBinding.pagView.apply {
                setRepeatCount(1)
                addListener(object : PAGViewListener {
                    override fun onAnimationEnd(p0: PAGView?) {
                        super.onAnimationEnd(p0)
                        mBinding.pagView.visibility = View.GONE
                    }
                })
                setScaleMode(PAGScaleMode.Zoom)
                play()
            }

        } else {
            mBinding.pagView.visibility = View.VISIBLE
        }
    }

    fun reset() {
        mConsumeAdapter.data.clear()
        mConsumeAdapter.notifyDataSetChanged()
        mBinding.tvUserCount.text = ""
        mBinding.tvUserCount.visibility = GONE
    }

    fun setOnAvatarClientListener(listener: OnClickListener) {
        mBinding.avAvatar.setOnSingleClickListener {
            listener.onClick(it)
        }
    }

    fun setOnFollowerClickListener(listener: OnClickListener) {
        mBinding.pagView.setOnSingleClickListener {
            listener.onClick(it)
        }
    }

    fun setOnConsumeItemClickListener(listener: (Int, LiveConsumptionUserVo) -> Unit) {
        mConsumeAdapter.setOnItemClickListener { _, _, position ->
            DebounceHelper.singleClick {
                val item = mConsumeAdapter.getItem(position)
                listener(position, item)
            }
        }
    }

    //点击在线人数
    fun setOnOnlineClickListener(listener: () -> Unit) {
        mBinding.tvUserCount.setOnSingleClickListener {
            listener.invoke()
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        parent.requestDisallowInterceptTouchEvent(true)
        return super.dispatchTouchEvent(ev)
    }
}